<template>
  <div class="upload-container">
    <!-- 上传成功后显示的图片预览 -->
    <div v-if="imageUrl" class="image-preview-container">
      <img :src="imageUrl" alt="Uploaded image" class="preview-image" />
      <!-- 遮罩层 -->
      <div class="image-overlay" @click="triggerReplaceUpload" v-if="!uploadLoading">
        <!-- <button class="delete-button" @click.stop="handleImageRemove" title="delete image">
          <el-icon><CircleClose /></el-icon>
        </button> -->
        <div class="reupload">
          <svg
            width="25"
            height="25"
            viewBox="0 0 25 25"
            fill="none"
            xmlns="http://www.w3.org/2000/svg">
            <path
              fill-rule="evenodd"
              clip-rule="evenodd"
              d="M14.9697 5.59467C15.2626 5.30178 15.7374 5.30178 16.0303 5.59467L18.2803 7.84467C18.5732 8.13756 18.5732 8.61244 18.2803 8.90533L16.0303 11.1553C15.7374 11.4482 15.2626 11.4482 14.9697 11.1553C14.6768 10.8624 14.6768 10.3876 14.9697 10.0947L15.9393 9.125H7.25117C6.45604 9.12766 5.69422 9.4447 5.13196 10.007C4.56969 10.5692 4.25265 11.331 4.25 12.1262V12.875C4.25 13.2892 3.91421 13.625 3.5 13.625C3.08579 13.625 2.75 13.2892 2.75 12.875V12.125L2.75 12.1228C2.75356 10.931 3.22858 9.78902 4.0713 8.9463C4.91402 8.10357 6.05598 7.62856 7.24776 7.625L7.25 7.625H15.9393L14.9697 6.65533C14.6768 6.36244 14.6768 5.88756 14.9697 5.59467ZM21.5 11.375C21.9142 11.375 22.25 11.7108 22.25 12.125V12.875L22.25 12.8772C22.2464 14.069 21.7714 15.211 20.9287 16.0537C20.086 16.8964 18.944 17.3714 17.7522 17.375L17.75 17.375H9.06066L10.0303 18.3447C10.3232 18.6376 10.3232 19.1124 10.0303 19.4053C9.73744 19.6982 9.26256 19.6982 8.96967 19.4053L6.71967 17.1553C6.42678 16.8624 6.42678 16.3876 6.71967 16.0947L8.96967 13.8447C9.26256 13.5518 9.73744 13.5518 10.0303 13.8447C10.3232 14.1376 10.3232 14.6124 10.0303 14.9053L9.06066 15.875H17.7489C18.544 15.8723 19.3058 15.5553 19.868 14.993C20.4303 14.4307 20.7474 13.6689 20.75 12.8737V12.125C20.75 11.7108 21.0858 11.375 21.5 11.375Z"
              fill="white" />
          </svg>
          <div class="overlay-text">Reupload</div>
        </div>
      </div>

      <!-- 预览区域的loading显示 -->
      <div v-if="uploadLoading" class="global-loading-overlay">
        <el-icon class="is-loading"><Loading color="#ffffff" /></el-icon>
      </div>
    </div>

    <!-- 上传组件，仅在没有图片时显示 -->
    <div v-else>
      <el-upload
        class="upload-el"
        drag
        :disabled="uploadLoading"
        :show-file-list="false"
        :file-list="fileList"
        :http-request="handleCustomUpload"
        :on-remove="handleRemove"
        :before-upload="beforeUpload"
        :limit="1"
        accept="image/*">
        <!-- 上传loading显示 -->
        <div v-if="uploadLoading" class="loading-overlay">
          <el-icon class="is-loading"><Loading color="#CBCBCB" /></el-icon>
        </div>
        <template v-else>
          <SvgIcon name="ai-upload" size="24" />
          <div class="el-upload__text">Click or drag to upload</div>
          <div class="el-upload__tip">JPG/PNG less than 20M</div>
        </template>
      </el-upload>
    </div>

    <!-- 隐藏的文件输入，用于触发重新上传 -->
    <input
      ref="fileInputRef"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleFileChange" />
  </div>
</template>

<script setup lang="ts">
  import { ref, defineEmits, defineProps, computed } from 'vue';
  import { UploadFile, UploadRawFile } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import { BaseAPI } from '@/api/base';
  import { Loading } from '@element-plus/icons-vue';
  import SvgIcon from './SvgIcon.vue';
  import imageCompression from 'browser-image-compression';
  import { useUserStore } from '@/store/user';

  // 定义组件接收的 props
  const props = defineProps<{
    modelValue?: string;
  }>();

  // 定义组件发送的事件
  const emit = defineEmits<{
    'update:modelValue': [value: string];
    'upload-success': [file: UploadFile, response: any];
    'upload-error': [error: any];
  }>();

  // 文件列表状态
  const fileList = ref<UploadFile[]>([]);
  const uploadLoading = ref(false);
  const fileInputRef = ref<HTMLInputElement>();

  const userStore = useUserStore();

  // 从props计算当前图片URL
  const imageUrl = computed(() => props.modelValue);

  // 定义图片压缩配置
  const compressionOptions = {
    maxSizeMB: 1, // 最大文件大小（MB）
    // maxWidthOrHeight: 1920, // 最大宽度或高度
    useWebWorker: true, // 使用Web Worker提高性能
  };

  // 图片压缩函数
  const compressImage = async (file: File) => {
    try {
      // 如果文件已经很小，不需要压缩
      if (file.size < 1024 * 1024) {
        // 小于1MB的文件不压缩
        return file;
      }

      const compressedFile = await imageCompression(file, compressionOptions);
      // console.log('原始文件大小:', (file.size / 1024 / 1024).toFixed(2), 'MB');
      // console.log('压缩后文件大小:', (compressedFile.size / 1024 / 1024).toFixed(2), 'MB');

      // 创建一个新的File对象，确保与原始文件结构兼容
      // 保留原始文件的名称和类型，但使用压缩后的内容
      const blob = await compressedFile.arrayBuffer();
      return new File([blob], file.name, { type: file.type });
    } catch (error) {
      console.error('图片压缩失败:', error);
      // 如果压缩失败，返回原始文件
      return file;
    }
  };

  // 文件上传前的验证方法
  const beforeUpload = (file: UploadRawFile) => {
    // 定义最大文件大小 (20MB)
    const maxSize = 20 * 1024 * 1024;

    if (!userStore.checkAndShowLogin()) {
      return false;
    }

    // 检查文件大小
    if (file.size && file.size > maxSize) {
      ElMessage.error('The file size cannot exceed 20M');
      return false;
    }

    // 验证通过，继续上传
    return true;
  };

  // 自定义上传方法
  const handleCustomUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;

    try {
      uploadLoading.value = true;

      // 压缩图片
      const compressedFile: any = await compressImage(file);

      // 调用实际的文件上传接口
      const response = await BaseAPI.uploadFile(compressedFile);

      // 假设响应中包含文件的URL
      const fileUrl = response.data.url;

      // 更新文件列表
      fileList.value = [
        {
          name: file.name,
          url: fileUrl,
          uid: file.uid || `file_${Date.now()}`,
          raw: compressedFile,
          status: 'ready',
        },
      ];

      // 通知父组件更新图片URL
      emit('update:modelValue', fileUrl);
      emit('upload-success', fileList.value[0], response);

      // 通知组件上传成功
      onSuccess(response);
    } catch (error) {
      // 通知组件上传失败
      onError(error);
      emit('upload-error', error);
      console.error('文件上传失败:', error);
    } finally {
      uploadLoading.value = false;
    }
  };

  // 处理文件删除
  const handleRemove = (file: UploadFile) => {
    const index = fileList.value.findIndex((item) => item.uid === file.uid);
    if (index !== -1) {
      fileList.value.splice(index, 1);
      // 通知父组件清除图片URL
      emit('update:modelValue', '');
    }
    return true;
  };

  // 处理图片删除（从预览区域）
  const handleImageRemove = () => {
    fileList.value = [];
    emit('update:modelValue', '');
  };

  // 触发替换上传
  const triggerReplaceUpload = () => {
    fileInputRef.value?.click();
  };

  // 处理文件选择变化（替换上传）
  const handleFileChange = async (event: Event) => {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const file = input.files[0];

      // 先验证文件
      if (!beforeUpload(file as UploadRawFile)) {
        // 重置input，允许再次选择同一个文件
        input.value = '';
        return;
      }

      // 构造上传选项
      const uploadOptions = {
        file,
        onSuccess: () => {},
        onError: () => {},
      };

      // 执行上传
      await handleCustomUpload(uploadOptions);

      // 重置input，允许再次选择同一个文件
      input.value = '';
    }
  };
</script>

<style lang="scss" scoped>
  .upload-container {
    position: relative;
    width: 100%;
    height: 200px;
    border-radius: 8px;
    overflow: hidden;
  }

  .upload-el {
    :deep(.el-upload-dragger) {
      border-radius: 8px;
      padding: 24px;
      border: none;
      height: 200px;
      background: #404040;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      &:hover {
        opacity: 0.98;
      }
    }

    .el-upload__text {
      font-size: 16px;
      color: #f8f8f8;
      font-weight: 600;

      line-height: 100%;
      margin: 4px 0px;
    }
    .el-upload__tip {
      font-size: 14px;
      color: #cbcbcb;
      font-weight: 400;

      line-height: 100%;
    }
  }

  // 图片预览容器样式
  .image-preview-container {
    position: relative;
    height: 100%; // 可根据需要调整高度
    overflow: hidden;
    background: #404040;
    .global-loading-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
      background: rgba(0, 0, 0, 0.45);
    }
  }

  // 预览图片样式
  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  // 遮罩层样式
  .image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: white;
  }

  // 鼠标悬浮时显示遮罩层
  .image-preview-container:hover .image-overlay {
    opacity: 1;
  }

  .reupload {
    display: flex;
    flex-direction: column;
    align-items: center;

    // 遮罩层提示文本样式
    .overlay-text {
      font-weight: 600;
      font-style: SemiBold;
      font-size: 16px;
      line-height: 100%;
      letter-spacing: 0%;
      text-align: right;
      margin-top: 8px;
      text-decoration: underline;
    }
  }
  // 删除按钮样式
  .delete-button {
    position: absolute;
    top: 8px;
    right: 8px;
    background-color: rgba(255, 255, 255, 0.2);
    border: none;
    border-radius: 50%;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: white;
    transition: background-color 0.3s ease;
    z-index: 1;

    &:hover {
      background-color: rgba(255, 255, 255, 0.3);
    }
  }
</style>
